<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: Michael_xu | gengxiaoxu@5kcrm.com
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;
use app\admin\model\User;
use Exception;
use think\Hook;
use think\Request;
use think\Db;
use PHPExcel_IOFactory;

//外勤
class Personnel extends ApiCommon
{
    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/
    public function _initialize()
    {
        $action = [
            'permission'=>['getpersonnel'],
            'allow'=>['commission','flowlist']
        ];
        Hook::listen('check_auth',$action);
        $request = Request::instance();
        $a = strtolower($request->action());
        if (!in_array($a, $action['permission'])) {
            parent::_initialize();
        } else {
            $param = Request::instance()->param();
            $this->param = $param;
        }
    }

    /**
     * 外勤列表
     * @author Michael_xu
     * @return
     */
    public function index()
    {
        $PersonnelModel = model('Personnel');
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        $data = $PersonnelModel->getDataList($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 导出
     */
    public function export(){
        $param = $this->param;
        $userInfo = $this->userInfo;
        $param['user_id'] = $userInfo['id'];
        // 导出的字段列表
        $fieldModel = new \app\admin\model\Field();
        $field_list = $fieldModel->where(["types_id"=>18])->select();
        // 文件名
        $file_name = 'invoice'.date('Ymd');
        $export=new Finance();
        $export->exportCsv($file_name, $field_list, function($list) use ($param){
            $PersonnelModel = model('Personnel');
            $param["page"]=1;
            $param["limit"]=5000;
            $data = $PersonnelModel->getDataList($param);
            $list = $data["list"];
            return $list;
        });
    }
    /**
     * 外勤接收/或者完结
     * @author Michael_xu
     * @return
     */
    public function fieldreception()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $assignfieldModel = model('Assignfield');
        if (!$param['assignfield_id']) {
            return resultArray(['error' => '分配记录id为空']);
        }
        $status=$param["status"]?:0;
        $assignfield=$assignfieldModel->where(["assignfield_id"=>$param["assignfield_id"]])->find();
        if(empty($assignfield)){
            return resultArray(['error' =>"记录不存在"]);
        }
        if ($assignfield["admin_user_id"]!=$userInfo["id"]) return resultArray(['error' =>"该订单未分配给您"]);
        $contractModel = new \app\crm\model\Contract();
        $dataInfo = $contractModel->where(['contract_id' => $param["contract_id"]])->find();
        //判断权限
        if($dataInfo["state"]==1){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单未捡取"]);
        }
        /*if($dataInfo["check_status"]!=2){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单状态错误"]);
        }*/
        if($dataInfo["is_ok"]==1){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单已完结"]);
        }
        $group=db('admin_access')->where(['user_id'=>$userInfo["id"]])->where("group_id=31")->find();
        if(empty($group)) return resultArray(['error' => "只有外勤才能操作"]);
        if($status==1){
            //完结
            // $res=db('crm_assignfield_recorde')->where(["admin_user_id"=>$userInfo["id"],
            //     "contract_id"=>$assignfield["contract_id"],
            //     "status"=>0])->find();
            // if (empty($res))  return resultArray(['error' => "请先点击接收"]);
            $res=db('crm_assignfield_recorde')->where(["admin_user_id"=>$userInfo["id"],
                "contract_id"=>$assignfield["contract_id"],
                "assignfield_id"=>$param["assignfield_id"],
                "status"=>$status])->whereIn("state",[0,1])->find();
            if (!empty($res))  return resultArray(['error' => "您已操作"]);
        }else{
            $res=db('crm_assignfield_recorde')->where(["admin_user_id"=>$userInfo["id"],
                "contract_id"=>$assignfield["contract_id"],
                "assignfield_id"=>$param["assignfield_id"],
                "status"=>$status])->find();
            if (!empty($res))  return resultArray(['error' => "您已操作"]);
        }
        /*$recorde=db('crm_assignfield_recorde')->whereIn("state",[0,1])->where(["status"=>$status,"contract_id"=>$assignfield["contract_id"],"admin_user_id"=>$userInfo["id"]])->find();
        if($recorde)  return resultArray(['error' => "您已操作"]);*/
        Db::startTrans();
        try {
            $assignfield->status=1;
            //新增外勤记录
            $res=db('crm_assignfield_recorde')->insert([
                "admin_user_id"=>$userInfo["id"],
                "contract_id"=>$assignfield["contract_id"],
                "remark"=>$param["remark"]?:'',
                "status"=>$status,
                "createtime"=>time(),
                "assignfield_id"=>$param["assignfield_id"],
                "state"=>$status==1?0:1,
                "examine_time"=>time(),
            ]);
            if($status==1){
                //判断工单---所有分配外勤接收改变订单状态为执行中 ---state工单库状态：1=待捡取，2=待分配，3=待接收，4=执行中，5=待验收
                $count=$assignfieldModel->where(["contract_id"=>$assignfield["contract_id"]])->count();
                $recorde_count=db('crm_assignfield_recorde')->where(["contract_id"=>$assignfield["contract_id"],"status"=>1])->count("DISTINCT admin_user_id");
                if($count==$recorde_count){
                    $contractModel->where(['contract_id' => $param["contract_id"]])->update(["state"=>4]);
                }
                //$assignfield->status=2;
            }else{
                $assignfield->receive_time=time();
            }
            $assignfield->save();
            //如果分配的外勤都全部完成，就同步工单状态为已完成
            $notEndId=db('crm_assignfield_recorde')->where(["contract_id"=>$assignfield["contract_id"],"status"=>array("in",["0","2"])])->value("assignfield_recorde_id");
            if(!$notEndId){
                db("crm_contract")->where(["contract_id"=>$assignfield["contract_id"]])->update(["is_ok"=>1]);
            }
            if($status!=1){
                //点击接收---判断工单分配的所有人是否已点击接收
                $recorde_count=db('crm_assignfield_recorde')
                    ->where(["status"=>0,"contract_id"=>$assignfield["contract_id"]])
                    ->count("DISTINCT admin_user_id");
                $assignfield_count=$assignfieldModel
                    ->where(["contract_id"=>$assignfield["contract_id"]])
                    ->count("DISTINCT admin_user_id");
                if($recorde_count>=$assignfield_count){
                    //修改工单状态为执行中
                    $contractModel->where(["contract_id"=>$assignfield["contract_id"]])->update(["state"=>4]);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if($res){
            return resultArray(['data' => '成功']);
        }
    }
    /**
     * 检测工单状态
     * */
    private function check($param){
        $contractModel = model('Contract');
        if (!isset($param['contract_id'])) {
            return ["code"=>400,'error' => '请选择工单'];
        }
        $contract=$contractModel->where(["contract_id"=>$param['contract_id']])->find();
        if(empty($contract)){
            return ["code"=>400,'error' => '记录不存在'];
        }
        if($contract["crm_wvgjii"]=="记账"){
            return ["code"=>400,'error' => '记账订单不能参与外勤操作'];
        }
        if(empty($contract["butler_id"])){
            return ["code"=>400,'error' => '订单未捡取'];
        }
        return $contract;
    }
    /**
     * 审核外勤完结记录
     * */
    public function examine()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $assignfieldModel = model('Assignfield');
        if(!isset($param["state"])) return resultArray(['error' => '请选择审核状态']);
        $recorde=db('crm_assignfield_recorde')
            ->where(["assignfield_recorde_id"=>$param["assignfield_recorde_id"]])->find();
        if(!$recorde){
            return resultArray(['error' => '该数据不存在或已审核！']);
        }
        // $butler_id=$assignfieldModel->where(["assignfield_id"=>$recorde["assignfield_id"]])->value("butler_id");

        // if($butler_id != $userInfo["id"]){//判断只能是分配外勤主管(管家)才能审核
        //     return resultArray(['error' => '您没有审核权限！请通知该订单分配管家审核！']);
        // }
        $group = db('admin_access')->where(['user_id' => $userInfo["id"], "group_id" => "32"])->find();
        if (empty($group)) return resultArray(['error' => "您没有审核权限！请通知管家审核！"]);

        if($recorde["state"]!=0) return resultArray(['error' => '此记录已审核']);
        $param["contract_id"]=$recorde["contract_id"];
        $contract=$this->check($param);
        if(isset($contract["code"])){
            return resultArray(['error' => $contract["error"]]);
        }
        if($contract["butler_id"]!=$userInfo["id"] && !$group){
            return resultArray(['error' => '您不可审核此记录']);
        }

        $contractModel = model('Contract');
        $contract=$contractModel->where(["contract_id"=>$param['contract_id']])->find();
        $update["memo"]=$param["memo"];
        $update["state"]=$param["state"];
        $update["examine_time"]=time();

        db('crm_assignfield_recorde')->where(["assignfield_recorde_id"=>$param["assignfield_recorde_id"]])->update($update);
        if($param["state"]==1){
            //审核通过
            //计算办件时间
            $assignfieldModel = model('Assignfield');
            $assignfield=$assignfieldModel->where(["assignfield_id"=>$recorde["assignfield_id"]])->find();
            if($assignfield){
                $processing=abs(time()-$assignfield["receive_time"]);//办件时间；
                $processing=floor($processing/86400);
                $assignfield->ok_time=time();
                $assignfield->status=2;
                $assignfield->processing=$processing;
            }
            //审核通过---判断工单分配的所有人是否已点完结
            $recorde_count=db('crm_assignfield_recorde')
                ->where(["status"=>1,"contract_id"=>$assignfield["contract_id"],"state"=>1])
                ->count("assignfield_id");
            $assignfield_count=$assignfieldModel
                ->where(["contract_id"=>$assignfield["contract_id"]])
                ->count("assignfield_id");
            if($recorde_count>=$assignfield_count){
                //修改工单状态为已完结
                $contract->save(["is_ok"=>1]);
            }
            if($recorde_count>=$assignfield_count){
                //修改工单状态为待验收
                $contract->save(["state"=>5]);
            }
            $update=[];
            //类型:0=接收,1=已完结,2=跟进
            if(empty($recorde["status"])){
                $update["status"]=1;
                $update["receive_time"]=time();
            }
            if($recorde["status"]==1){
                //状态:0=待接收,1=未完结,2=已完结
                $update["status"]=2;
                $update["ok_time"]=time();
            }
            if(!empty($update)){
                db('crm_assignfield')->where(["assignfield_id"=>$recorde["assignfield_id"]])->update($update);
            }
        }
        return resultArray(['data' => '成功']);
    }
    /**
     * 外勤操作记录
     * */
    public function recordelog()
    {
        $param = $this->param;
        //$assignfieldModel = model('Assignfield');
        if (!$param['assignfield_id']) {
            return resultArray(['error' => '订单id为空']);
        }
        //$assignfield=$assignfieldModel->find($param['assignfield_id']);
        $list=db('crm_assignfield_recorde')
            ->field("assignfield_recorde_id,remark,from_unixtime(createtime, '%Y-%m-%d %H:%i:%s') createtime,status,state,memo,from_unixtime(examine_time, '%Y-%m-%d %H:%i:%s') examine_time")
            ->where(["assignfield_id"=>$param["assignfield_id"]])->select();
            /*->where(["admin_user_id"=>$assignfield["admin_user_id"],"contract_id"=>$assignfield["contract_id"]])*/
        return resultArray(['data' => $list]);
    }
    /**
     * （管家）填写外勤提成
     * 提成金额+核定成本不能大于回款
     * */
    public function commission()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $assignfieldModel = model('Assignfield');
        if (!$param['assignfield_id']) {
            return resultArray(['error' => '分配记录id为空']);
        }
        if ($param['money'] === false) {
            return resultArray(['error' => '请输入提成金额']);
        }
        $group=db('admin_access')->where(['user_id'=>$userInfo["id"],"group_id"=>"32"])->find();
        if(empty($group)) return resultArray(['error' => "只有管家才能填写提成"]);
        $assignfield=$assignfieldModel->where(["assignfield_id"=>$param["assignfield_id"]])->find();
        if($assignfield["butler_id"]!=$userInfo["id"]){//判断只能是分配外勤主管(管家)才能审核
            return resultArray(['error' => '您没有审核权限！请通知该订单分配管家审核！']);
        }
        if(empty($assignfield)){
            return resultArray(['error' =>"订单不存在"]);
        }
        /*if($assignfield["status"]!=2){
            return resultArray(['error' =>"该外勤订单未完结，不能填写提成金额"]);
        }*/

        $contractModel = new \app\crm\model\Contract();
        $dataInfo = $contractModel->where(['contract_id' => $assignfield["contract_id"]])->find();
        //判断权限
        if($dataInfo["state"]==1){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单未捡取"]);
        }
        /*if($dataInfo["check_status"]!=2){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单状态错误"]);
        }*/
        // if($dataInfo["is_ok"]==1){
        //     return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：合同工单已完结"]);
        // }
        if($dataInfo["butler_id"]!=$userInfo["id"]){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：您不能操作不属于您的订单"]);
        }
        //提成金额+核定成本不能大于回款
        $commission=db("crm_assignfield")->where(["contract_id"=>$assignfield["contract_id"]])->sum("money");
        $commission=$commission+($assignfield["money"]-$param["money"]);
        $crm_oeseng=$dataInfo["crm_oeseng"];//核定成本金额
        $collectionAmount=db("crm_finance")->where(["contract_id"=>$assignfield["contract_id"],"check_status"=>2,"order_type"=>"回款"])->sum("money");//该订单的回款金额
        $allowMoney=$collectionAmount-$crm_oeseng-$commission;
        if($allowMoney < 0){
            return resultArray(['error' => "'操作失败，错误原因：提成金额超出".abs($allowMoney)]);
        }
        $res=$assignfield->save(["money"=>$param["money"]]);
        if($res){
            return resultArray(['data' => '成功']);
        }
        return resultArray(['data' => '失败']);
    }
    //管家转移外勤办件给另外一个外勤人员
    public function transfer(){
        $param = $this->param;
        $userInfo = $this->userInfo;
        $assignfieldModel = model('Assignfield');
        $assignfield=$assignfieldModel->where(["assignfield_id"=>$param["assignfield_id"]])->find();
        if(empty($assignfield)){
            return resultArray(['error' =>"记录不存在"]);
        }
        $group=db('admin_access')->where(['user_id'=>$userInfo["id"],"group_id"=>"32"])->find();
        if(empty($group)) return resultArray(['error' => "只有管家才能才能转移外勤办件事项!"]);
        $res=$assignfield->save(["admin_user_id"=>$param["admin_user_id"]]);
        if($res){
            return resultArray(['data' => '转移成功！']);
        }
        return resultArray(['data' => '转移失败！']);
    }
    //获取工单的外勤分配记录
    public function allocationRecord(){
        $param = $this->param;
        $res=db("crm_assignfield")->alias("a")
            ->join('admin_user admin',"admin.id=a.admin_user_id","left")
            ->where(["contract_id"=>$param["contract_id"]])->field("admin.realname,a.name as title,from_unixtime(a.butler_time, '%Y-%m-%d %H:%i:%s') as allocate_time")->select();
        return resultArray(['data' => $res]);
    }
    /**
     * 填写跟进记录
     * */
    public function addflow()
    {
        $param = $this->param;
        $userInfo = $this->userInfo;
        $assignfieldModel = model('Assignfield');
        if (!$param['assignfield_id']) {
            return resultArray(['error' => '分配记录id为空']);
        }
        $assignfield=$assignfieldModel->where(["assignfield_id"=>$param["assignfield_id"]])->find();
        if(empty($assignfield)){
            return resultArray(['error' =>"记录不存在"]);
        }
        if ($assignfield["admin_user_id"]!=$userInfo["id"]) return resultArray(['error' =>"该订单未分配给您"]);
        $contractModel = new \app\crm\model\Contract();
        $dataInfo = $contractModel->where(['contract_id' => $param["contract_id"]])->find();
        //判断权限
        if($dataInfo["state"]==1){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单未捡取"]);
        }
        if($dataInfo["is_ok"]==1){
            return resultArray(['error' => "订单'".$dataInfo['name']."'操作失败，错误原因：订单已完结"]);
        }
        $group=db('admin_access')->where(['user_id'=>$userInfo["id"]])->where("group_id=31")->find();
        if(empty($group)) return resultArray(['error' => "只有外勤才能操作"]);
        if($assignfield["status"]!=1) return resultArray(['error' => "只有未完结才能填写跟进记录"]);
        //新增外勤记录
        $res=db('crm_assignfield_recorde')->insert([
            "admin_user_id"=>$userInfo["id"],
            "contract_id"=>$assignfield["contract_id"],
            "remark"=>$param["remark"]?:'',
            "status"=>2,
            "createtime"=>time(),
            "assignfield_id"=>$param["assignfield_id"],
            "state"=>1,
            "examine_time"=>time(),
        ]);
        if($res){
            return resultArray(['data' => '成功']);
        }
    }

    /**
     * 查找合同跟进记录
     * */
    public function flowlist()
    {
        $PersonnelModel = model('Personnel');
        $param = $this->param;
        if(!isset($param["contract_id"])) return resultArray(['error' => "订单id为空"]);
        $data = $PersonnelModel->getFlowList($param);
        return resultArray(['data' => $data]);
    }

    /**
     * 查找合同分配外勤
     * */
    public function getpersonnel()
    {
        $param = $this->param;
        if(!isset($param["contract_id"])) return resultArray(['error' => "订单id为空"]);
        $data=User::field("id,realname")->where("id in (".\app\crm\model\Assignfield::field("admin_user_id")->where(['contract_id'=>$param['contract_id']])->fetchsql()->select().")")->select();
        return resultArray(['data' => $data]);
    }


}